<template>
  <div style="max-width: 70%;margin: 10px auto 0;">
    <a-row>
      <a-card v-for="(value, key) in checkData" :title="key" :key="key" :bordered="false" style="width: 90%" :loading="table_loading">
        <!-- 使用新的 slot 语法 -->
        <template #extra>
          <div style="display: flex; gap: 8px;">
            <a-select allowClear  showSearch style="width: 15vw" size="small" placeholder="下游客户"
                      :filter-option="false"
                      @search="(value) => queryParams.searchText[key]=value"
                      :options="customizedFilterOptions(queryParams.searchText[key], groupedTradePartners)"
                      dropdownClassName="custom-dropdown"
                      v-model:value="queryParams.id_trader[key]">
            </a-select>
            <a-select style="width: 15vw" size="small" placeholder="入帐公司" v-model:value="queryParams.id_myCompany[key]" :options="companies">
            </a-select>
          </div>
        </template>
          <a-table size="small" :loading="table_loading" :columns="dynamicColumn(key, value)" :rowClassName="setRowStyle()"
             :data-source="errorFilter(key,value)" :pagination="{
                showTotal: (totalCount) => `共 ${totalCount} 条记录`,
                total: total[key]
            }"/>
      </a-card>
    </a-row>
    <a-row :gutter="[1,10]">
      <a-col :offset="10">
        <a-checkbox v-model:checked="onlyShowErrorRows">是否仅显示问题记录</a-checkbox>
        <a-checkbox v-model:checked="override">是否导入数据相同覆盖</a-checkbox>
      </a-col>
    </a-row>
    <a-row :gutter="16">
      <a-col :offset="10" :span="2">
        <a-button style="margin-left: 8px" @click="prevStep">上一步</a-button>
      </a-col>
      <a-col :offset="0" :span="3">
        <a-button :loading="loading" type="primary" :disabled="noPass" @click="save">导入</a-button>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import { postAction } from "@/utils/request.js";
import {customizedFilterOptions} from "@/utils/my.js";
import useUserStore from '@/store/modules/user'

// dict
const currentUser = useUserStore()

// 定义 props
const props = defineProps(['checkData', 'checkResult', 'groupedTradePartners', 'companies', 'queryParams', 'table_loading']);
// 定义 emits
const emit = defineEmits(['nextStep', 'prevStep']);

// 定义本地状态
const rowKey = ref('id');
const searchTextForTraders = ref('');
const onlyShowErrorRows = ref(false);
const override = ref(false);
const noPass = ref(false);
const total = ref({});
const loading = ref(false);
const columns = ref([
  {
    title: '主单号',
    dataIndex: '主单号',
  },
  {
    title: '日期',
    dataIndex: '日期',
  },
  {
    title: '始发港',
    dataIndex: '始发港',
  },
  {
    title: '目的港',
    dataIndex: '目的港',
  },
  {
    title: '件数',
    dataIndex: '件数',
    align: 'right',
  },
  {
    title: '重量',
    dataIndex: '重量',
    align: 'right',
  },
  {
    title: '计费重量',
    dataIndex: '计费重量',
    align: 'right',
  },
  {
    title: '单价',
    dataIndex: '单价',
    align: 'right',
  },
  {
    title: '总金额',
    dataIndex: '总金额',
    align: 'right',
  }
]);
// simple vars
const url = {
  import_from_excel_data: "/yg/import_from_excel_data"
}

// 定义计算属性
const fixKeys = computed(() => {
  const keys_already = columns.value.map((c) => c.title);
 // console.error("keys_already:", keys_already);
  return keys_already;
});

// 定义工具函数
function isValidBillNo(str) {
  // 使用正则表达式验证：^表示开头，[0-9a-zA-Z]表示数字或字母，{11}表示长度11，$表示结尾
  return /^[0-9a-zA-Z]{11}$/.test(str);
}

// 定义方法
const save = async () => {
  const data = {};
  console.log("this.queryParam:", props.queryParams);
  for (const k in props.checkData) {
    if (!props.queryParams.id_trader[k]) {
      message.error(`${k}，下游公司不能为空！`);
      return;
    }
    data[k] = [props.checkData[k], props.queryParams.id_trader[k], props.queryParams.id_myCompany[k], override.value];
  }
  console.log("data:", data);
  loading.value = true;
  //console.error(url.value.excel_data_import);
  try {
    const res = await postAction(url.import_from_excel_data, { "records": data, "create_by": currentUser.name, type: "checking_bill" });
    if (!res || !res.success) {
      message.warning("保存失败！");
      loading.value = false;
      return;
    }
    loading.value = false;
    nextStep();
  } catch (error) {
    message.warning("保存失败！");
    loading.value = false;
  }
};

const nextStep = () => {
  loading.value = true;
  setTimeout(() => {
    emit('nextStep');
  }, 1500);
};

const prevStep = () => {
  emit('prevStep');
};

const setRowStyle = () => {
  return (record) => { // 移除未使用的 index 和 i 变量
    const sum = Object.keys(record)
      .filter(key => fixKeys.value.indexOf(key) === -1)
      .reduce((acc, key) => {
        return acc + record[key];
      }, 0);
    const style = sum === 0 || !isValidBillNo(record['主单号']) ? 'ant-table-row-selected my-warning' : '';
    //console.error("style:", style);
    return style;
  };
};

const dynamicColumn = (key, value) => {
  const localColumns = columns.value.slice();
  console.log("columns:", JSON.stringify(localColumns));
  total.value[key] = value.length;
  console.log("this.total[key]:", total.value[key]);
  if (value && value[0]) {
    Object.keys(value[0]).forEach((k) => {
      if (fixKeys.value.indexOf(k) === -1) {
        if (k.indexOf("备注") === -1) {
          localColumns.push({
            title: k,
            dataIndex: k,
            align: 'right',
          });
        } else {
          localColumns.push({
            title: k,
            dataIndex: k,
            align: 'left',
          });
        }
      }
    });
  }
  console.log("columns:", JSON.stringify(localColumns));
  return localColumns;
};

const errorFilter = (fileName, data) => {
  const errors = data.filter((row) => {
    // 主单号规范; 总金额 不能为0
    const sum = Object.keys(row)
      .filter(key => fixKeys.value.indexOf(key) === -1)
      .reduce((acc, key) => {
        return acc + row[key];
      }, 0);
    // console.log(row['主单号']);
    // console.log(isValidBillNo(row['主单号']));
    return sum === 0 || !isValidBillNo(row['主单号']);
  });
  if (errors && errors.length > 0) noPass.value = true;
  // console.log("this.noPass:", noPass.value);
  props.checkResult[fileName] = errors;
  return onlyShowErrorRows.value ? errors : data;
};
</script>
